package com.hjb.service.controller.Wechat;

import java.io.IOException;
import java.io.PrintWriter;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.hjb.service.Wechat.WechatService;
import com.hjb.service.Wechat.WechatUserInfoService;
import com.hjb.service.annotation.H5Code;
import com.hjb.service.annotation.HttpCode;
import com.hjb.service.annotation.LogInfo;
import com.hjb.service.annotation.LogType;
import com.hjb.service.config.properties.WxProperties;
import com.hjb.service.config.session.JXSession;
import com.hjb.service.domain.AccessToken;
import com.hjb.service.domain.Member;
import com.hjb.service.domain.siteuser.SiteUser;
import com.hjb.service.user.UserService;
import com.hjb.service.utils.StringUtil;
import com.hjb.service.wx.Sign;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 * 微信授权 js-sdk
 * 
 * @ClassName: WeixinController
 * @Description: TODO(公众号端微信交互)
 * @author <a href="mailto:125671254@qq.com">Pan Xinwen</a>
 * @date 2017年4月23日 上午11:56:17
 */
@RestController
@RequestMapping("")
public class WechatController {
	private Logger log = LoggerFactory.getLogger(WechatController.class);
	@Autowired
	private WechatService wechatService;
	
	@Autowired
	private WxProperties wxProperties;
	
	@Autowired
	private WechatUserInfoService wechatUserInfoService;
	
	@Value("${jixing.service.h5.url}")
	private String jixingServiceH5Url;
	
	@SuppressWarnings("rawtypes")
	@LogInfo(logType = LogType.新增, operationContent = "生成二维码")
	@PostMapping("/getErweima")
	@ResponseBody
	@ApiOperation("生成二维码")
	@ApiImplicitParams({ @ApiImplicitParam(paramType = "query", dataType = "String", name = "phonenumber", value = "租户手机号", required = false)})
	public ResponseEntity getErweima(@RequestParam(value = "phonenumber", required = false) String phonenumber){
		wechatService.getErweimaTicket(phonenumber);
		return  ResponseEntity.ok("1");
	}
	
    /**
     * 验证微信服务器
     * 
     * @param response
     * @param signature
     * @param timestamp
     * @param nonce
     * @param echostr
     * @throws NoSuchAlgorithmException 
     */
    @RequestMapping(value = "/wechat", method = RequestMethod.GET)
    public String wechatService(
            @RequestParam(value = "signature", required = false) String signature, @RequestParam String timestamp,
            @RequestParam String nonce, @RequestParam String echostr) throws NoSuchAlgorithmException {
    	 return wechatService.wxListener(signature, timestamp, nonce, echostr);
    }
    
    /**
     * 接收来自微信发来的消息
     * 
     * @param out
     * @param request
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "/wechat", method = RequestMethod.POST)
    public void wechatServicePost(PrintWriter out, HttpServletRequest request, HttpServletResponse response) {
        String responseMessage = wechatService.processRequest(request);
        out.print(responseMessage);
        out.flush();
    }
    
	
	/**
	 * 获取js sdk 认证信息
	 * @author
	 * @param request
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	@RequestMapping("getSign")
	public String getSign(HttpServletRequest request) {

//		String url = request.getScheme() + "://";
//		url += request.getHeader("host");
//		url += request.getRequestURI();
//		if (request.getQueryString() != null) {
//			url += "?" + request.getQueryString();
//		}
		String shareType = request.getParameter("shareType");
		String url = request.getParameter("url");
		String isActivity = request.getParameter("isActivity");
		String zfurl = request.getParameter("zfurl");
		log.info("校验签名的url============"+url);
		//获取ticket
		List<AccessToken> list= wechatService.getAccess_token();
		Map<String, String> ret = Sign.sign(list.get(0).getJsapiTicket(), url);
		log.info("计算出的签名："+ret.toString());
		JSONObject json = new JSONObject();
		for (Map.Entry entry : ret.entrySet()) {
			log.info((entry.getKey() + "=============" + entry.getValue()));
			json.put(entry.getKey().toString(), entry.getValue());
		}
		
		//活动页
		if(isActivity !=null && isActivity.equals("1")){
			url = wxProperties.getBase_url()+"/share?inviteCode="+request.getSession().getAttribute("userId")+"&zfurl="+zfurl;
		}else{
			if(shareType !=null && shareType.equals("1")){
				url = wxProperties.getBase_url()+"/share?shareType=1&houseId="+request.getParameter("houseId")+"&inviteCode="+request.getSession().getAttribute("userId");
			}else{
				url = wxProperties.getBase_url()+"/share?inviteCode="+request.getSession().getAttribute("userId");
			}
		}
		
		
		log.info("分享出去的url===="+url);
		
		json.put("shareUrl", url);
		json.put("appId", wxProperties.getAppId());
		
		return json.toString();
	}

	// 微信授权回调地址
	@RequestMapping("/redirect")
	@LogInfo(logType = LogType.回调, operationContent = "用户授权回调")
	public void redirect(HttpServletRequest request, HttpServletResponse response) {
		 String user_access_token = wechatService.redirect(request);
		 JSONObject json = new JSONObject(user_access_token);
		 String opendId = (String) json.get("openid");
//		 //查询是否存在该用户
		 SiteUser user = wechatUserInfoService.getUserInfoByOpendId(opendId.toString());
		 JXSession session = new JXSession();
		 session.setOpenid(user.getOpenid());
		 session.setUserId(user.getUserId());
		 session.setMobile(user.getMobile());
		 
		 String h5 = request.getParameter("state");
		 
		 if(StringUtil.isEmpty(h5)){
			 jixingServiceH5Url+=H5Code.H5(Integer.parseInt(h5)); 
		 }
//		 String userId= StringUtil.get22Str();
//		 String parentId = request.getSession().getAttribute("parentId")==null?"":request.getSession().getAttribute("parentId").toString();
//		 if(list.size() == 0) {
//			 Member member = new Member();
//			 member.setId(userId);
//			 member.setWxOpenId(opendId);
//			 member.setUserAccessToken(json.getString("access_token"));
//			 member.setModTime(new Date());
//			 member.setAddTime(new Date());
//			 member.setAmount(0);
//			 if(!parentId.equals("")){
//				 member.setParentId(parentId);
//			 }
//			 //创建用户
//			 userService.createUser(member);
//			 request.getSession().setAttribute("userId", userId);
//		 }else{
//			 Member member = list.get(0);
//			 if(!parentId.equals("")){
//				 member.setParentId(parentId); 
//			 }
//			 
//			 member.setUserAccessToken(json.getString("access_token"));
//			 userService.updateToken(member);
//			 request.getSession().setAttribute("userId", member.getId());
//		 }
//		 //登录
//		 request.getSession().setAttribute("openId", opendId);
//
//		String curl = request.getSession().getAttribute("curl") + "";
//
//		log.info("转发的地址===========" + curl);

		try {
			response.sendRedirect(jixingServiceH5Url+"?session="+JSON.toJSONString(session));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	//微信授权
	@RequestMapping("/snsapibase")
	public void snsapibase(@RequestParam(value = "redirect_uri",required = false)String redirect_uri,HttpServletResponse response){
		
		wechatService.snsapibase(redirect_uri,response);
		
	}

	public static void main(String[] args) {
		 JXSession session = new JXSession();
		 session.setOpenid("otE8W1eWNrukqGb6Ql2L1cy9MeCQ");
		 session.setUserId( new Integer(1000171));
		 session.setMobile("19919866605");
		 
		 System.out.println(JSON.toJSONString(session));
	}
	
}
